<template>
  <div>
    <el-row :gutter="15">
      <el-col :span="24">
        <el-card  class="search-form">
          <div slot="header" class="clearfix">提货调度</div>
          <el-form ref="searchForm" class="el-form-col" :model="search">
            <el-row :gutter="15" style="position:relative;">
              <el-col :lg="4" :md="6">
                <el-form-item prop="orderNo">
                  <el-input type="textarea" v-model="search.orderNo" :rows="4" placeholder="订单号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6">
                <el-form-item prop="pickUpName">
                  <el-input v-model="search.pickUpName" placeholder="客户姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6">
                <el-form-item prop="pickUpPhone">
                  <el-input v-model="search.pickUpPhone" placeholder="客户电话"></el-input>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6" class="hidden-lg-only hidden-xl-only">
                <el-form-item>
                  <el-row :gutter="5" class="search-btns">
                    <el-col :span="12">
                      <el-button type="primary" :loading="searchLoading" plain native-type="submit" @click.prevent="searchFunc(search)">搜索</el-button>
                    </el-col>
                    <!--<el-col :span="8">-->
                      <!--<el-button type="primary" @click.prevent="searchOpen = !searchOpen">-->
                        <!--{{ searchOpen ? '收起' : '展开' }}-->
                      <!--</el-button>-->
                    <!--</el-col>-->
                    <el-col :span="12">
                      <el-button @click.prevent="reset('searchForm')">重置
                      </el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6">
                <el-form-item prop="addressArr">
                  <Cascade-address v-model="search.addressArr" placeholder="客户地址" changeOnSelect :level="3"/>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6">
                <el-form-item
                  prop="workerName">
                  <el-select
                    placeholder="服务方"
                    v-model="search.workerName"
                    filterable
                    reserve-keyword
                    :remote-method="remoteMethod"
                  >
                    <el-option
                      v-for="item in options4"
                      :key="item.workerId"
                      :label="item.workerName"
                      :value="item.workerName">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6" class="hidden-md-only hidden-sm-only">
                <el-form-item>
                  <el-row :gutter="5" class="search-btns">
                    <el-col :span="12">
                      <el-button type="primary" :loading="searchLoading" plain native-type="submit" @click.prevent="searchFunc(search)">搜索</el-button>
                    </el-col>
                    <!--<el-col :span="8">-->
                      <!--<el-button type="primary" @click.prevent="searchOpen = !searchOpen">-->
                        <!--{{ searchOpen ? '收起' : '展开' }}-->
                      <!--</el-button>-->
                    <!--</el-col>-->
                    <el-col :span="12">
                      <el-button @click.prevent="reset('searchForm')">重置
                      </el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6">
                <el-form-item prop="workerPhone">
                  <el-input v-model="search.workerPhone" placeholder="服务方电话"></el-input>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6">
                <el-form-item prop="timeIntervalCode">
                  <el-select v-model="search.timeIntervalCode" placeholder="预约时段">
                    <el-option v-for="item in timeIntervalArr"
                               :key="item.value"
                               :label="item.text"
                               :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6">
                <el-form-item prop="orderState">
                  <el-select v-model="search.orderState" filterable placeholder="订单状态">
                    <el-option v-for="item in orderStateArr"
                               :key="item.value"
                               :label="item.text"
                               :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :lg="4" :md="6">
                <el-form-item prop="serviceState">
                  <el-select v-model="search.serviceState" filterable placeholder="服务状态">
                    <el-option v-for="item in serviceStateArr"
                               :key="item.value"
                               :label="item.text"
                               :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" style="line-height: 30px">
        <el-card class="box-card">
          <el-row :gutter="10">
            <el-col :xl="4" :lg="6" :md="5">
              <span class="dispatch-header-text">
                当日订单数：<span class="font-orange">{{headData.dispatchOrderNumAll}}</span>单
              </span>
            </el-col>
            <el-col :xl="4" :lg="6" :md="6">
              <span class="dispatch-header-text">
                待调度：<span class="font-red">{{headData.dispatchOrderNumN}}</span>单
              </span>
            </el-col>
            <el-col :xl="4" :lg="6" :md="6">
              <span class="dispatch-header-text">
                已调度：<span class="green-color">{{headData.dispatchOrderNumY}}</span>单
              </span>
            </el-col>
            <el-col :xl="3" :lg="6" :md="7">
              <span class="dispatch-header-text font-orange">
                待出发：<span>{{headData.nextOutBoundCount}}</span>单
              </span>
            </el-col>
            <el-col :xl="3" :lg="6" :md="5">
              <span class="dispatch-header-text font-orange">
                待上门：<span>{{headData.nextHouseCallCount}}</span>单
              </span>
            </el-col>
            <el-col :xl="3" :lg="6" :md="6">
              <span class="dispatch-header-text font-orange">
                待签收：<span>{{headData.nextSignCount}}</span>单
              </span>
            </el-col>
            <el-col :xl="3" :lg="6" :md="6">
              <span class="dispatch-header-text font-orange">
                 已完成：{{headData.achieveCount}}单
              </span>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header" class="clearfix">
            <el-row>
              <el-col :span="4">
                <span>待调度订单</span>
              </el-col>
              <el-col :span="3">
                <el-checkbox :indeterminate="checkAllIndeterminate" v-model="checkAll" @change="handleCheckAllChange">
                  全选
                </el-checkbox>
              </el-col>
              <el-col :span="7">
                已选体积：{{checkedVolume}} m³
              </el-col>
              <el-col :span="6">
                已选单数：{{checkedOrderCount}} 单
              </el-col>
              <el-col :span="4">
                <el-button class="pull-right" size="mini" type="primary" @click.prevent="addWorkerShow">选择服务方</el-button>
              </el-col>
            </el-row>
          </div>
          <Order-component
            ref="OrderComponent"
            :orderDataArr="waitDispatchData"
            :dispatchStage="false"
            v-model="checkedInteractive"
            @refresh="init"
          ></Order-component>
          <Pagination style="margin-top: 20px" class="pull-right" :total-item="totalItem" @pagination="pagination"
                      @sizeChange="sizeChange" :perItem="params.pageSize"></Pagination>
          <div class="clearfix"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header" class="clearfix">
            <el-row :gutter="10">
              <el-col :span="5">已调度订单</el-col>
              <el-col :span="8"><span class="green-color">总服务方:{{headData.workerNum}} 位</span></el-col>
            </el-row>
          </div>
          <div v-for="(item, index) in dispatchPlan" :key="index" style="margin-bottom: 20px">
            <div class="already-dispatch-title">
              <el-row>
                <el-col :lg="9" :md="12">
                  <span>调度编号：{{item.code}}</span>
                </el-col>
                <el-col :lg="5" :md="8">
                  <span>总体积：{{item.totalVolume}} m³</span>
                </el-col>
                <el-col :lg="1" :md="4" class="hidden-lg-only hidden-xl-only">
                  <i class="pull-right el-icon-delete" @click="deleteDispatchPlan(item)"></i>
                </el-col>
                <el-col :lg="5" :md="8">
                  <span>总包件：{{item.totalPackage}} 件</span>
                </el-col>
                <el-col :lg="4" :md="8">
                  <span>总单数：{{item.totalOrderNum}}单</span>
                </el-col>
                <el-col :lg="1" :md="4" class="hidden-md-only hidden-sm-only">
                  <i class="pull-right el-icon-delete" @click="deleteDispatchPlan(item)"></i>
                </el-col>
              </el-row>
            </div>
            <div class="already-dispatch-body dispatch-lineHeight">
              <div style="background: #f0f1f4; padding: 5px">
                <el-row>
                  <el-col :span="4">
                    <el-button size="mini" :disabled="addButtonLoading" type="success"
                               @click="editDispatchPlan('add', item)">添加
                      <i class="el-icon-arrow-right"></i>
                    </el-button>
                  </el-col>
                  <el-col :span="7">服务方：{{item.workerName}} <a href="javascript:;"><i class="el-icon-edit blue-color"
                                                                                     @click="editWorkerShow(item)"></i></a>
                  </el-col>
                  <el-col :span="7">手机号：{{item.workerPhone}}</el-col>
                  <el-col :span="6">车牌号：{{item.plateNumber}}</el-col>
                </el-row>
                <el-row>
                  <el-col :span="4">
                    <el-button size="mini" :disabled="addButtonLoading" type="danger"
                               @click="editDispatchPlan('edit', item)">
                      <i class="el-icon-arrow-left"></i>
                      移除
                    </el-button>
                  </el-col>
                  <el-col :span="7">待出发：{{item.nextOutBoundCount}} 单</el-col>
                  <el-col :span="7">待签收：{{item.nextSignCount}} 单</el-col>
                  <el-col :span="6">已完成：{{item.achieveCount}} 单</el-col>
                </el-row>
              </div>
              <Order-component
                ref="completeOrderComponent"
                :isMore="item.isMore || false"
                :dispatchStage="true"
                :orderDataArr="item.pickUpOrderList"
              ></Order-component>
              <div style="width: 100%;height: 40px;text-align: center;line-height: 40px;background: #f0f1f4"
                   v-if="item.pickUpOrderList.length > 4">
                <span v-if="!item.isMore">共{{item.pickUpOrderList.length}}条 <a @click="unfold(item)"
                                                                               href="javascript:;">点击显示全部</a></span>
                <a v-if="item.isMore" @click="unfold(item)" href="javascript:;">点击收起</a>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <Check-worker-modal
      ref="CheckWorkerModal"
      @checkWorker="addWorker"
    ></Check-worker-modal>
  </div>
</template>
<script>
import {copy, merge, dotData, confirm} from '@/utils'
import {unixTimestampFilter, filterDataBaseDictionary} from '@/filters'
import moment from 'moment'
import Pagination from '@/components/Pagination'
import OrderComponent from '@/views/oms/dispatch/deliveryDispatch/OrderComponent'
import CheckWorkerModal from '@/views/oms/dispatch/deliveryDispatch/CheckWorkerModal'
import {getSubDictListOfParentCode, getOrderState, getDispatchServiceState} from '@/utils/selectOptions'

export default {
  name: 'deliveryDispatchIndex',
  filters: {
    unixTimestampFilter,
    filterDataBaseDictionary
  },
  components: {
    Pagination,
    OrderComponent,
    CheckWorkerModal
  },
  data() {
    return {
      searchLoading: false,
      totalItem: 0,
      params: {
        pageSize: 20,
        pageNum: 1
      },
      searchOpen: false,
      search: {
        orderNo: '',
        pickUpName: '',
        pickUpPhone: '',
        workerName: '',
        workerPhone: '',
        addressArr: [],
        timeIntervalCode: '',
        orderState: '',
        merchantName: '',
        statTime: '',
        endTime: '',
        serviceState: ''
      },
      headData: {},
      waitDispatchData: [],
      dispatchPlan: [],
      completeDispatchData: [],
      checkAllWaitData: [], // 待调度选中订单
      checkedInteractive: {},
      checkAll: '',
      checkedVolume: 0,
      checkedOrderCount: 0,
      isaddWorker: true,
      dispatchId: '',
      options4: [],
      timeIntervalArr: [],
      orderStateArr: [],
      serviceStateArr: [],
      frequency: false,
      addButtonLoading: false
    }
  },
  mounted() {
    this.remoteMethod()
  },
  created() {
    getSubDictListOfParentCode('TERMINAL_TIME_INTERVAL').then(arr => {
      this.timeIntervalArr = arr
    })
    getOrderState().then(arr => {
      this.orderStateArr = arr
    })
    getDispatchServiceState().then(arr => {
      this.serviceStateArr = arr
    })
    this.init()
  },
  computed: {},
  watch: {
    'checkedInteractive.checkAll'(val, oldVal) {
      this.checkAll = val
    },
    'checkedInteractive.checkAllIndeterminate'(val, oldVal) {
      this.checkAllIndeterminate = val
    },
    'checkedInteractive.checkedVolume'(val, oldVal) {
      this.checkedVolume = val
    },
    'checkedInteractive.checkedOrderCount'(val, oldVal) {
      this.checkedOrderCount = val
    }
  },
  methods: {
    init() {
      this.getHead()
      this.getDispatchData()
      this.checkAll = false
      this.checkAllIndeterminate = false
      this.checkedVolume = 0
      this.checkedOrderCount = 0
    },
    disabledDate(time) {
      return time.getTime() < moment(this.search.statTime).format('x')
    },
    pagination(page) {
      this.params.pageNum = page
      this.init()
    },
    sizeChange(size) {
      this.params.pageSize = size
      this.init()
    },
    remoteMethod(query) {
      if (query !== '') {
        this.$ajax.get('/ms-warehouse-order/pickUp-dispatch/get-worker-all-list').then(response => {
          this.options4 = response.data || []
        })
      } else {
        this.options4 = []
      }
    },
    searchFunc() {
      this.init()
    },
    reset() {
      this.$refs.searchForm.resetFields()
    },
    handleCheckAllChange(val) {
      this.waitDispatchData.forEach(item => {
        if (val) {
          item.checkOrder = true
        } else {
          item.checkOrder = false
        }
        this.$refs.OrderComponent.checkAllServiceChange()
      })
    },
    unfold(item) {
      item.isMore = !item.isMore
    },
    getHead() {
      this.$ajax.table('/ms-terminal-order/pickUp-dispatch/get-head').then(response => {
        this.headData = response.data || {}
      })
    },
    getDispatchData() {
      let data = copy(this.search, true)
      data = merge(data, this.params)
      data.pickUpProvinceNo = dotData(data.addressArr, '[0]')
      data.pickUpCityNo = dotData(data.addressArr, '[1]')
      data.pickUpDistrictNo = dotData(data.addressArr, '[2]')
      delete data.addressArr
      this.searchLoading = true
      this.$ajax.table('/ms-terminal-order/pickUp-dispatch/get-order-list', data).then(response => {
        let data = copy(response.data || [])
        this.totalItem = response.totalItem
        data.forEach(item => {
          item.checkOrder = false
        })
        this.waitDispatchData = data
      }).finally(_ => {
        this.searchLoading = false
      })
      data.pageSize = 1000
      this.$ajax.table('/ms-terminal-order/pickUp-dispatch/get-dispatch-list', data).then(response => {
        let data = copy(response.data || [])
        data.forEach(item => {
          item.isMore = false
          item.pickUpOrderList.forEach(v => {
            v.checkOrder = false
            if (v.isDepart) { // 包含已出发的订单
              item.isDepart = v.isDepart // 处理禁止点击删除计划
            }
          })
        })
        this.dispatchPlan = data
      })
    },
    addWorkerShow() {
      this.isaddWorker = true
      this.checkAllWaitData = this.$refs.OrderComponent.getCheckData()
      console.log('this.checkAllWaitData', this.checkAllWaitData)
      if (!this.checkAllWaitData.length) {
        this.$message({
          type: 'warning',
          message: '请选择待调度订单'
        })
        return
      }
      this.$refs.CheckWorkerModal.show()
    },
    editWorkerShow(item) {
      this.isaddWorker = false
      this.dispatchId = item.id
      this.$refs.CheckWorkerModal.show()
    },
    addWorker(row) {
      let data = {}
      let _url = ''
      data.workerId = row.workerId
      if (this.isaddWorker) {
        _url = '/ms-terminal-order/pickUp-dispatch/save-dispatch'
        data.serviceOrderIds = this.checkAllWaitData
      } else {
        _url = '/ms-terminal-order/pickUp-dispatch/update-dispatch-worker'
        data.dispatchId = this.dispatchId
      }
      this.$ajax.post(_url, data).then(response => {
        this.frequency = false
        if (response.success) {
          this.$message({
            type: 'success',
            message: '操作成功！'
          })
          this.$refs.CheckWorkerModal.hide()
          this.init()
        }
      })
    },
    deleteDispatchPlan(item) {
      if (item.isDepart) {
        this.$message({
          type: 'warning',
          message: '该计划内包含有已出发订单，不能直接删除！'
        })
        return
      }
      let data = {}
      data.dispatchId = item.id
      confirm('删除该订单调度将返回待调度列表中！', '提示', {
        type: 'warning',
        confirmButtonLoading: true,
        confirmCallBack: ({confirmButtonLoadingClose, close}) => {
          this.$ajax.post('/ms-terminal-order/pickUp-dispatch/delete-dispatch', data).then(response => {
            if (response.success) {
              close()
              this.$message({
                type: 'success',
                message: '删除成功！'
              })
              this.init()
            } else {
              confirmButtonLoadingClose()
            }
          }).finally(_ => {
            confirmButtonLoadingClose()
          })
        }
      })
    },
    editDispatchPlan(type, data) {
      let obj = {}
      obj.dispatchId = data.id
      obj.serviceOrderIds = []
      let message = ''
      if (type === 'add') {
        obj.updateType = 1
        obj.serviceOrderIds = this.$refs.OrderComponent.getCheckData()
        message = '请选择需要调度的订单'
      } else {
        data.pickUpOrderList.forEach(item => {
          if (item.checkOrder) {
            obj.serviceOrderIds.push(item.serviceOrderId)
          }
        })
        obj.updateType = 2
        message = '请选择需要变更的已调度的订单'
      }
      console.log('obj.serviceOrderIds', obj.serviceOrderIds)
      if (!obj.serviceOrderIds.length) {
        this.$message({
          type: 'warning',
          message: message
        })
        return
      }
      this.addButtonLoading = true
      this.$ajax.post('/ms-terminal-order/pickUp-dispatch/update-dispatch', obj).then(response => {
        this.addButtonLoading = false
        if (response.success) {
          this.$message({
            type: 'success',
            message: '变更计划成功！'
          })
          this.init()
        }
      })
    }
  }
}
</script>
